package com.softer.wxzj.service.impl;/**
 * @author Gong Zhiyang
 * @date 2019/6/26
 */

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.softer.wxzj.common.entity.CommonResult;
import com.softer.wxzj.common.entity.Page;
import com.softer.wxzj.common.enums.NumStrEnum;
import com.softer.wxzj.common.enums.NumberEnum;
import com.softer.wxzj.common.enums.ShiroResultEnum;
import com.softer.wxzj.common.error.CourseException;
import com.softer.wxzj.common.util.ShiroUserUtil;
import com.softer.wxzj.entity.AccCalculateInterestInfo;
import com.softer.wxzj.entity.AccInterestConfig;
import com.softer.wxzj.entity.BaseBankInfo;
import com.softer.wxzj.entity.BaseContractorBankInfo;
import com.softer.wxzj.entity.base.BaseEntity;
import com.softer.wxzj.mapper.*;
import com.softer.wxzj.service.AccKeepAccountService;
import com.softer.wxzj.service.BaseContractorBankInfoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Gong Zhiyang
 * @date 2019/6/26
 */
@Service
public class BaseContractorBankInfoServiceImpl implements BaseContractorBankInfoService {
    @Autowired
    private BaseContractorBankInfoMapper baseContractorBankInfoMapper;
    @Autowired
    private AccKeepAccountService accKeepAccountService;
    @Autowired
    private BaseBuildInfoMapper baseBuildInfoMapper;
    @Autowired
    private BaseBuildInfoServiceImpl baseBuildInfoService;
    @Autowired
    private SysCoreParamMapper sysCoreParamMapper;
    @Autowired
    private BaseBankInfoMapper baseBankInfoMapper;
    @Autowired
    private AccCalculateInterestInfoMapper accCalculateInterestInfoMapper;
    @Autowired
    private AccCalculateInterestDetailLogMapper accCalculateInterestDetailLogMapper;
    @Autowired
    private AccCalculateInterestDetailMapper accCalculateInterestDetailMapper;
    @Autowired
    private AccInterestConfigMapper accInterestConfigMapper;
    @Autowired
    private AccInterestConfigServiceImpl accInterestConfigService;
    @Autowired
    private DicContentMapper dicContentMapper;

    /**
     * 新增承办银行
     *
     * @param baseContractorBankInfo 承办银行信息
     * @return 新增结果
     */
    @Override
    @Transactional
    public CommonResult insert(BaseContractorBankInfo baseContractorBankInfo) {
        //校验银行是否添加过
        String bankId = baseContractorBankInfoMapper.checkBankId(baseContractorBankInfo.getBankId());
        if (StringUtils.isNotBlank(bankId)) {
            return CommonResult.ResponseResult(NumberEnum.ZERO.getNum(), "该银行已经添加过");
        }
        //校验银行账户是否添加过
        String id = baseContractorBankInfoMapper.checkBankAcc(baseContractorBankInfo.getBankAcc());
        if (StringUtils.isNotBlank(id)) {
            return CommonResult.ResponseResult(NumberEnum.ZERO.getNum(), "该银行账户已经添加过");
        }
        String userName = ShiroUserUtil.getUserName();
        baseContractorBankInfo.setCreater(userName);
        baseContractorBankInfo.setModifier(userName);
        if (StringUtils.isBlank(baseContractorBankInfo.getOpenDate())) {
            baseContractorBankInfo.setOpenDate(null);
        }
        String firstLevelCode = sysCoreParamMapper.getParamValueByCode("62");
        BaseBankInfo baseBankInfo = baseBankInfoMapper.getInfo(baseContractorBankInfo.getBankId());
        String codeNo = sysCoreParamMapper.getParamValueByCode("59");
        if (null != codeNo && codeNo.equals(NumStrEnum.ONE.getNum())) {
            String code = baseBuildInfoService.addInster(firstLevelCode, baseBankInfo.getBankName());
            baseContractorBankInfo.setFinanceNo(code);
        }
        if (null == baseContractorBankInfo.getMoney()) {
            baseContractorBankInfo.setMoney(BigDecimal.ZERO);
        }
        if (null == baseContractorBankInfo.getBalance()) {
            baseContractorBankInfo.setBalance(baseContractorBankInfo.getMoney());
        }
        String oldBase = baseContractorBankInfoMapper.getMinTime();
        interest(oldBase, baseContractorBankInfo.getCommissioningDate());
        //结息
        int num = baseContractorBankInfoMapper.insert(baseContractorBankInfo);
        return CommonResult.ResponseResult(num);
    }

    @Override
    @Transactional
    public CommonResult update(BaseContractorBankInfo baseContractorBankInfo) {
        BaseContractorBankInfo baseOld = baseContractorBankInfoMapper.getInfoBybankId(baseContractorBankInfo.getBankId());
        BigDecimal oldMoney = baseOld.getMoney();
        if (StringUtils.isBlank(baseContractorBankInfo.getOpenDate())) {
            baseContractorBankInfo.setOpenDate(null);
        }
        if (null == baseContractorBankInfo.getBalance()) {
            baseContractorBankInfo.setBalance(BigDecimal.ZERO);
        }
        if (null == baseContractorBankInfo.getMoney()) {
            baseContractorBankInfo.setMoney(BigDecimal.ZERO);
        }
        baseContractorBankInfo.setModifier(ShiroUserUtil.getUserName());
        String oldBase = baseContractorBankInfoMapper.getMinTime();
        BigDecimal banlace = baseContractorBankInfo.getBalance().subtract(oldMoney).add(baseContractorBankInfo.getMoney());
        baseContractorBankInfo.setBalance(banlace);
        int num = baseContractorBankInfoMapper.updateByPrimaryKey(baseContractorBankInfo);
        String base = baseContractorBankInfoMapper.getMinTime();
        //accInterestConfig
        //修改结息

        interest(oldBase, base);
        return CommonResult.ResponseResult(num);
    }

    /**
     * 结息是不是第一条  要不要修改
     *
     * @param oldBase
     * @param base
     */
    private void interest(String oldBase, String base) {
        if (StringUtils.isBlank(oldBase)) {
            oldBase = "1000-01-01";
        }
        LocalDate beginDateTime = LocalDate.parse(oldBase, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        LocalDate baseDate = LocalDate.parse(base, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        String oldYear = oldBase.substring(0, 4);
        String newYear = base.substring(0, 4);
        if (!accInterestConfigMapper.getList().isEmpty()) {
            if (!beginDateTime.isEqual(baseDate)) {
                //查询是不是第一条数据
                List<AccCalculateInterestInfo> acc = accCalculateInterestInfoMapper.getCountNum();
                if (null == acc) {
                    //修改结息日期
                    if (!oldYear.equals(newYear)) {
                        accCalculateInterestInfoMapper.updateYear(newYear);
                    }
                    //todo 删除结息记录
                    int nu = accCalculateInterestInfoMapper.selectAdvChange();
                    if (nu > 0) {
                        throw new CourseException(ShiroResultEnum.FAIL.getCode(), "有正在结算数据请稍后重试");
                    }
                    //清空上次结息
                    List<AccCalculateInterestInfo> lists = accCalculateInterestInfoMapper.selectAdv();
                    for (AccCalculateInterestInfo ac : lists) {
                        accCalculateInterestDetailLogMapper.deleteByRateNo(ac.getRateNo());
                        accCalculateInterestDetailMapper.deleteByRateNo(ac.getRateNo());
                        //删除当前结息
                        accCalculateInterestInfoMapper.delete(ac.getId());
                    }
                    List<AccInterestConfig> list = accInterestConfigMapper.getList();
                    if (!list.isEmpty()) {
                        AccCalculateInterestInfo a = accCalculateInterestInfoMapper.selectMin();
                        if (null == a) {
                            AccCalculateInterestInfo accCalculateInterestInfo = accInterestConfigService.setAccCalculateInterestInfo(list.get(0), newYear);
                            accCalculateInterestInfoMapper.insert(accCalculateInterestInfo);
                        } else {
                            for (int j = 0; j < list.size(); j++) {
                                LocalDate beginTime = LocalDate.parse("2020-" + list.get(j).getInterestDate(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                                LocalDate nowTime = LocalDate.parse("2020-" + a.getInterestDate(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                                if (beginTime.isBefore(nowTime)) {
                                    AccCalculateInterestInfo accCalculateInterestInfo = accInterestConfigService.setAccCalculateInterestInfo(list.get(j), newYear);
                                    accCalculateInterestInfoMapper.insert(accCalculateInterestInfo);
                                    break;
                                }
                                continue;
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 删除承办银行详情
     *
     * @param id 承办银行ID
     * @return 删除结构
     */
    @Override

    public CommonResult delete(String id) {
        BaseContractorBankInfo baseContractorBankInfo = baseContractorBankInfoMapper.selectByPrimaryKey(id);
        int num = baseBuildInfoMapper.selectCountBank(baseContractorBankInfo.getBankId());
        if (num != 0) {
            return CommonResult.ResponseResult(NumberEnum.ZERO.getNum(), "该银行账户已经使用过");
        }
        num = baseContractorBankInfoMapper.deleteByPrimaryKey(id);
        return CommonResult.ResponseResult(num);
    }

    @Override
    public PageInfo<BaseContractorBankInfo> getList(Page page, BaseContractorBankInfo baseContractorBankInfo) {
        return null;
    }

    /**
     * 查询承办银行列表
     *
     * @param page                   分页实体
     * @param baseContractorBankInfo 查询实体
     * @param fuzzy                  模糊查询字段
     * @return 承办银行列表
     */
    @Override
    public PageInfo<BaseContractorBankInfo> getList(Page page, BaseContractorBankInfo baseContractorBankInfo, String fuzzy) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<BaseContractorBankInfo> list;
        if (StringUtils.isNotBlank(fuzzy)) {
            list = baseContractorBankInfoMapper.fuzzySearch(fuzzy);
        } else {
            list = baseContractorBankInfoMapper.getList(baseContractorBankInfo);
        }
        //TODO 重新计算余额
        PageInfo<BaseContractorBankInfo> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public BaseContractorBankInfo getInfo(String id) {
        BaseContractorBankInfo baseContractorBankInfo = baseContractorBankInfoMapper.selectByPrimaryKey(id);
        baseContractorBankInfo.setNo(1);
        int num = baseBuildInfoMapper.selectCountBank(baseContractorBankInfo.getBankId());
        if (num != 0) {
            baseContractorBankInfo.setNo(0);
        }
        return baseContractorBankInfo;
    }

    /**
     * 查询承办银行下拉列表
     *
     * @return 承办银行列表
     */
    @Override
    public List<BaseBankInfo> getAllList() {
        List<BaseBankInfo> list = baseContractorBankInfoMapper.getAllList();
        return list;
    }

    @Override
    public List<BaseBankInfo> getAllListSelect() {
        BaseEntity baseEntity = accKeepAccountService.addSelect();
        List<BaseBankInfo> list = new ArrayList<>();
        if (StringUtils.isNotBlank(baseEntity.getZoneCode())) {
            list = baseContractorBankInfoMapper.getAllList();
        } else {
            BaseBankInfo b = baseContractorBankInfoMapper.selectBankNameById(baseEntity.getBankId());
            list.get(0).setId(baseEntity.getBankId());
            list.get(0).setBankName(b.getBankName());
        }
        return list;
    }
}
